//
//  TBBTagView.m
//  MuYing
//
//  Created by tbb on 2019/12/30.
//  Copyright © 2019 TBB. All rights reserved.
//

#import "TBBTagView.h"
#import "TBBTagModel.h"
#import "TBBTagModel.h"
@interface TBBTagView ()
/** 状态 */
@property (nonatomic, assign) ZYTagViewState state;
//起始点
@property (nonatomic, assign) CGPoint panTmpPoint;

@property (nonatomic, strong) UIView * titleView;
@property (nonatomic, strong) UIView * lineView;
@property (nonatomic, assign) CGFloat titleViewW;
//titleLb宽
@property (nonatomic, assign) CGFloat titleLbW;
@property (nonatomic, strong) UIButton * reversalBtn;

@property (nonatomic, strong) UIButton * deleteBtn;

@property (nonatomic, strong) UILabel * titleLb;

@end

@implementation TBBTagView

- (instancetype)initWithFrame:(CGRect)frame title:(NSString *)title state:(ZYTagViewState)state {
    self = [super initWithFrame:frame];
    
    if (self) {
        self.layer.cornerRadius = 4.0;
        self.backgroundColor = UIColor.whiteColor;
               
        _titleView = [[UIView alloc] init];
        _titleView.backgroundColor = HexColorA(0x000000, 0.5);
        _titleView.layer.cornerRadius = ktitleViewH / 2.0;
        _titleView.layer.borderWidth = 1.0;
        _titleView.layer.borderColor = UIColor.whiteColor.CGColor;
               
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = UIColor.whiteColor;

        UIButton *reversalBtn = [UIButton buttonWithType:0];
        [reversalBtn addTarget:self action:@selector(reversalAction:) forControlEvents:(UIControlEventTouchUpInside)];
        reversalBtn.frame = CGRectMake(0, 0, self.width+4, self.width+4);
        self.reversalBtn = reversalBtn;
               
        _titleLb = [[UILabel alloc] init];
        _titleLb.font = kSystemMedium(12);
        _titleLb.textColor = UIColor.whiteColor;
        _titleLb.textAlignment = NSTextAlignmentCenter;
        _titleLb.text = title;
        
        [_titleLb sizeToFit];
        CGFloat lbW = _titleLb.width;
        self.titleLbW = lbW;
        self.titleViewW = lbW + 24;
        _titleLb.frame = CGRectMake(12, 0, lbW, ktitleViewH);
        
        if (state == ZYTagViewStateArrowLeft) {
            //初始点在左边。
            _titleView.frame = CGRectMake(kLineViewW+kPointWidth, 30, self.titleViewW, ktitleViewH);
            _lineView.frame = CGRectMake(self.width, self.height/2.0, kLineViewW, 1);
        }else if(state == ZYTagViewStateArrowRight){
            _titleView.frame = CGRectMake(-(kLineViewW+self.titleViewW), 30, self.titleViewW, ktitleViewH);
            _lineView.frame = CGRectMake(-kLineViewW, self.height/2.0, kLineViewW, 1);
        }

        _titleView.centerY = self.height / 2.0;
        [self addSubview:_lineView];
        [self addSubview:_titleView];
        [self addSubview:reversalBtn];
        [_titleView addSubview:_titleLb];
    }
    return self;
}

-(void)deleteAction:(UIButton *)sender {
    //NSLog(@"-%s-",__func__);
    if (self.deleteAction) {
        self.deleteAction();
    }
    [self removeFromSuperview];
}
-(void)showDeleteBtnAction:(UIButton *)sender {
    if (_deleteBtn) {
        [self recoverAction];
    }else{
        CGFloat textViewX = self.titleView.frame.origin.x;
        _deleteBtn = [UIButton buttonWithType:0];
         [_deleteBtn setImage:YQIMG(@"publish_delete_tag_icon") forState:(UIControlStateNormal)];
         //_deleteBtn.hidden = YES;
         [_deleteBtn addTarget:self action:@selector(deleteAction:) forControlEvents:(UIControlEventTouchUpInside)];
         _deleteBtn.layer.cornerRadius = _deleteBtn.height / 2.0;
         _deleteBtn.clipsToBounds = true;
        [self addSubview:_deleteBtn];
        CGFloat deleteBtnW = ktitleViewH-2;
        self.titleView.width += deleteBtnW;
        CGFloat x = self.frame.origin.x;
        if (textViewX > 0) {
            CGFloat superViewW = self.superview.width;
            if (x >= superViewW - (kXSpace+self.titleView.width+kLineViewW+kPointWidth)) {
                self.titleView.width = self.titleViewW;
                self.titleLb.width = self.titleLbW - deleteBtnW;
            }
            //圆点在左边
            _deleteBtn.frame = CGRectMake(kLineViewW+kPointWidth+self.titleView.width-ktitleViewH, -1, deleteBtnW, deleteBtnW);
        }else{
            if (x <= (self.titleView.width + kLineViewW + kXSpace)) {
                self.titleView.width = self.titleViewW;
                self.titleLb.width = self.titleLbW - deleteBtnW;
            }
            self.titleView.left = -(kLineViewW+self.titleView.width);
           _deleteBtn.frame = CGRectMake(-(kLineViewW+1+deleteBtnW), -1, deleteBtnW, deleteBtnW);
        }
        _deleteBtn.centerY = self.height / 2.0;
    }
}
//还原
-(void)recoverAction{
    CGFloat textViewX = self.titleView.left;
    self.titleView.width = self.titleViewW;
    self.titleLb.width = self.titleLbW;
    self.titleLb.left = 12;
    if (textViewX < 0) {
        self.titleView.left = -(kLineViewW+self.titleViewW);
    }
    [self.deleteBtn removeFromSuperview];
    _deleteBtn = nil;
}
#pragma mark --添加手势
- (void)setupGesture
{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showDeleteBtnAction:)];
    [self.titleView addGestureRecognizer:tap];

    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
    [self addGestureRecognizer:pan];
}
//翻转
-(void)reversalAction:(UIButton *)sender{
    [self recoverAction];
    CGFloat superViewW = self.superview.width;
    //CGFloat superViewH = self.superview.height;
    CGFloat x = self.frame.origin.x;
    //CGFloat y = self.frame.origin.y;
    CGFloat textViewX = self.titleView.frame.origin.x;
    //CGFloat textViewY = self.titleView.frame.origin.y;
    
    CGFloat tagW = kPointWidth + kLineViewW + self.titleViewW;
    CGFloat __block minWith =  0.0;
    [UIView animateWithDuration:0.3 animations:^{
        if (0 < textViewX) {
            /**点在左边*/
            //圆点所在的位置不够titleView翻转
            minWith =  kXSpace + tagW-kPointWidth;
            if (x < minWith) {
                self.left = x +  tagW-kPointWidth;
            }
            self.titleView.left = -(kLineViewW + self.titleViewW);
            self.lineView.left = -kLineViewW;

        }else{
        //点在右边
            //圆点所在的位置不够titleView翻转
            minWith = superViewW - (tagW + kXSpace);
            if (x > minWith) {
                self.left = x - tagW + kPointWidth;
            }
            self.titleView.left = kLineViewW+kXSpace;
            self.lineView.left = self.width;
        }
    }];
}
//拖动事件
- (void)handlePanGesture:(UIPanGestureRecognizer *)pan
{
    [self recoverAction];
    CGPoint panPoint = [pan locationInView:self.superview];
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            //隐藏收藏按键
            //[self hiddenDeleteBtn];
            [self.superview bringSubviewToFront:self];
            //起始位置
            self.panTmpPoint = [pan locationInView:self];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [self changeLocationWithGestureState:UIGestureRecognizerStateChanged
                                      locationPoint:CGPointMake(panPoint.x - self.panTmpPoint.x, panPoint.y - self.panTmpPoint.y)];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            [self changeLocationWithGestureState:UIGestureRecognizerStateEnded
                                      locationPoint:CGPointMake(panPoint.x - self.panTmpPoint.x, panPoint.y - self.panTmpPoint.y)];
            
            self.panTmpPoint = CGPointZero;
        }
            break;
        default:
            break;
    }
}
-(void)setIsEditEnabled:(BOOL)isEditEnabled {
    _isEditEnabled = isEditEnabled;
    if(isEditEnabled) {
        // 手势处理
        [self setupGesture];
    };
    self.reversalBtn.userInteractionEnabled = self.isEditEnabled;
}
- (void)changeLocationWithGestureState:(UIGestureRecognizerState)gestureState locationPoint:(CGPoint)point
{
    
    if (self.isEditEnabled == NO) {
        return;
    }
    
    //CGPoint referencePoint = point;//CGPointMake(0, point.y);
    CGFloat referenceX = point.x;
    CGFloat referenceY = point.y;
    CGFloat superViewW = self.superview.width;
    CGFloat superViewH = self.superview.height;
    CGFloat textViewX = self.titleView.frame.origin.x;
    
    if (textViewX > 0) {
        if (referenceX < kXSpace) {
            referenceX = kXSpace;
        }else if (referenceX > superViewW - kXSpace - self.titleViewW - kLineViewW - kPointWidth){
            referenceX = superViewW - kXSpace - self.titleViewW - kLineViewW - kPointWidth;
        }
    }else{
        if (referenceX > superViewW - kXSpace - kPointWidth) {
            referenceX = superViewW - kXSpace - kPointWidth;
        }else if(referenceX < kXSpace+self.titleViewW+kLineViewW){
            referenceX = kXSpace+self.titleViewW+kLineViewW;
        }
    }
    
    if (referenceY < (kXSpace +  ktitleViewH/2.0) - kPointWidth/2.0) {
        referenceY = (kXSpace +  ktitleViewH/2.0) - kPointWidth/2.0;
    }else if (referenceY > superViewH - kXSpace  - ktitleViewH + (ktitleViewH -kPointWidth)/2.0){
        referenceY = superViewH - kXSpace  - ktitleViewH + (ktitleViewH -kPointWidth)/2.0;
    }
    // 更新位置
    self.arrowPoint = CGPointMake(referenceX, referenceY);;

}

#pragma mark - getter and setter

- (CGPoint)arrowPoint
{
    return self.origin;
}

-(CGPoint)arrowCenter {
    return self.center;
}

-(TBBTagModel *)tagModel {
    TBBTagModel *tagModel = [TBBTagModel new];
    tagModel.pointState = self.pointState;
    tagModel.arrowCenter = self.arrowCenter;
    tagModel.arrowPoint = self.arrowPoint;
    
    CGFloat superViewW = self.superview.width;
    CGFloat superViewH = self.superview.height;
    CGFloat centerX = self.arrowCenter.x;
    CGFloat centerY = self.arrowCenter.y;
    CGFloat proportionX = centerX / superViewW;
    CGFloat proportionY = centerY / superViewH;
    //比例
    tagModel.arrowCenterProportion = ZYPositionProportionMake(proportionX, proportionY);
    tagModel.title = self.titleLb.text;
    return tagModel;
}

-(ZYTagViewState)pointState {
    if (self.titleView.frame.origin.x > 0) {
        return ZYTagViewStateArrowLeft;
    }else{
        return ZYTagViewStateArrowRight;
    }
}

- (void)setArrowPoint:(CGPoint)arrowPoint
{
    
    CGRect rect = CGRectMake(arrowPoint.x, arrowPoint.y, self.width, self.width);
    
    self.frame = rect;
}

//*处理手势冲突*/
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event {
    UIView * view = [super hitTest:point withEvent:event];
    if (view == nil) {
        for (UIView * subView in self.subviews) {
            // 将坐标系转化为自己的坐标系
            CGPoint tp = [subView convertPoint:point fromView:self];
            if (CGRectContainsPoint(subView.bounds, tp)) {
                view = subView;
            }
        }
    }
    return view;
}


@end

